import dayjs from 'dayjs'
import { useEffect, useState } from 'react'

import { getDeliveryOrderNursingWorkerPageListApi } from '@/api/pcs/pcsCompanionOrder'
import AekForm from '@/components/AekForm'
import AekModal, { PromiseThen } from '@/components/AekModal'
import AekTable from '@/components/AekTable'
import SearchForm from '@/components/SearchForm'
import EditDrawer from '@/pages/pcs/pcsNursingWorkers/components/EditDrawer'
import { defaultPageSize, getPagination, message } from '@/utils/antdHelper'
import { PCS_COMPANION_PERIOD_ENUM, PCS_COMPANION_STATUS_ENUM } from '@/utils/enum'
import { requestWithTry } from '@/utils/request'

import DatePickerWithSelect from '../DatePickerWithSelect'

const SelNursingWorkerModal = ({
  oldNursingWorkeId,
  companionType,
  companionCompanyId,
  patientName,
  phoneNo,
  orderNo,
  isChange = false,
  startDate,
  startPeriod,
  endDate,
  endPeriod,
}) => {
  const [form] = AekForm.useForm()

  const [loading, setLoading] = useState(false)
  const [list, setList] = useState([])
  const [searchParams, setSearchParams] = useState({})
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: defaultPageSize,
    total: 0,
  })
  const [selList, setSelList] = useState([])

  const getList = async () => {
    setLoading(true)
    const params = {
      companionType,
      companionCompanyId,
      ...searchParams,
      ...pagination,
    }
    const { data } = await requestWithTry(getDeliveryOrderNursingWorkerPageListApi, params).finally(() => {
      setLoading(false)
    })
    const { content, current, pageSize, total } = data
    setList(content)
    setPagination({
      current,
      pageSize,
      total,
    })
  }

  useEffect(() => {
    getList()
  }, [JSON.stringify(searchParams), JSON.stringify(pagination)])

  /** @type {import("@/components/SearchForm").SearchFormProps} */
  const searchProps = {
    searchParams,
    formData: [{ field: 'name', label: '护工姓名', component: { name: 'Input' } }],
    onSearch: values => {
      setSearchParams(values)
      setPagination({ ...pagination, current: 1 })
    },
  }

  const handleDetail = async row => {
    await EditDrawer.PromiseThen({
      row,
      view: true,
    })
  }

  /** @type {import("@/components/AekTable").AekTableProps} */
  const tableProps = {
    showConfig: false,
    configKey: 'SelNursingWorkerModal',
    loading,
    rowKey: 'id',
    dataSource: list,
    columns: [
      {
        title: '护工信息',
        dataIndex: 'name',
        render: (text, row) => <a onClick={() => handleDetail(row)}>{text}</a>,
      },
      { title: '手机号', dataIndex: 'phoneNo' },
      {
        title: '陪护状态',
        dataIndex: 'companionStatus',
        render: text => PCS_COMPANION_STATUS_ENUM.getText(text),
      },
      {
        title: '陪护信息',
        key: 'infos',
        width: 400,
        render: (_, { places, serviceDateTimeList, companionComboNames }) =>
          places?.length
            ? places.map((item, index) => (
                <div
                  key={index}
                  className='b-b-1px b-b-solid b-b-#f0f0f0 py6px first:pt0 last:b-b-0 last:pb0 flex items-center'
                >
                  <div className='w-100px'>{item}</div>
                  <div className='ml10px w-140px'>{serviceDateTimeList[index]}</div>
                  <div className='ml10px w-100px'>{companionComboNames[index]}</div>
                </div>
              ))
            : '-',
      },
      // {
      //   title: '陪护地点',
      //   dataIndex: 'places',
      //   render: list => (
      //     <div className='flex h-full flex-col'>
      //       {list?.map((item, index) => (
      //         <div key={index} className='flex-grow-1'>
      //           {item}
      //         </div>
      //       ))}
      //     </div>
      //   ),
      // },
      // {
      //   title: '陪护时间',
      //   width: 160,
      //   dataIndex: 'serviceDateTimeList',
      //   render: list => list?.map((item, index) => <div key={index}>{item}</div>),
      // },
      // {
      //   title: '陪护套餐',
      //   dataIndex: 'companionComboNames',
      //   render: list => list?.map((item, index) => <div key={index}>{item}</div>),
      // },
    ],
    rowSelection: {
      type: 'radio',
      fixed: true,
      getCheckboxProps: item => ({
        disabled: item.id === oldNursingWorkeId,
      }),
      selectedRowKeys: selList.map(({ id }) => id),
      onSelect(record) {
        setSelList([record])
      },
    },
    pagination: getPagination(pagination, (current, pageSize) => {
      setPagination({ ...pagination, current, pageSize })
    }),
    beforePagination: `当前选择：${selList[0]?.name || ''}`,
  }

  /** @type {import("@/components/AekForm").FormDataProps[]} */
  const formData = [
    {
      label: '生效时间',
      field: 'effective',
      formItemProps: {
        getValueFromEvent: values => {
          if (values?.datePicker) {
            return { ...values, select: PCS_COMPANION_PERIOD_ENUM.BEFORE12 }
          }
        },
        rules: [
          { required: true, message: ' ' },
          {
            validator: async (rule, value) => {
              if (!value || !value?.datePicker || !value?.select) {
                return Promise.reject('请选择生效时间')
              }
              Promise.resolve()
            },
          },
        ],
      },
      component: (
        <DatePickerWithSelect
          selectProps={{ disabled: true }}
          disabledDate={current => {
            if (!current) return
            let disabled = false
            // 开始那天在今天或者之后，则开始那天不可选择
            if (dayjs(startDate).startOf('d') >= dayjs().startOf('d')) {
              disabled = current < dayjs(startDate).add(1, 'd').startOf('d')
            }
            // 开始那天在今天之前
            if (dayjs(startDate).startOf('d') < dayjs().startOf('d')) {
              // 现在时间在12点之前
              if (dayjs().hour() < 12) {
                disabled = current < dayjs().startOf('d')
              } else {
                disabled = current < dayjs().add(1, 'd').startOf('d')
              }
            }
            if (disabled) return true

            if (!endDate) {
              return disabled
            }

            // 结束那天在12之前
            if (endPeriod === PCS_COMPANION_PERIOD_ENUM.BEFORE12) {
              disabled = current > dayjs(endDate).add(-1, 'd').endOf('d')
            } else {
              disabled = current > dayjs(endDate).endOf('d')
            }
            return disabled
          }}
          disabledSelect={optionValue => {
            if (optionValue === PCS_COMPANION_PERIOD_ENUM.BEFORE12) {
              let _date = Math.max(dayjs(startDate).startOf('d'), dayjs().startOf('d'))
              if (startPeriod === PCS_COMPANION_PERIOD_ENUM.AFTER12) {
                return _date.valueOf() === form.getFieldValue('effective')?.datePicker?.startOf('d').valueOf()
              }
              if (
                form.getFieldValue('effective')?.datePicker?.startOf('d').valueOf() === dayjs().startOf('d').valueOf()
              ) {
                return dayjs().hour() < 12
              }
            }
            if (optionValue === PCS_COMPANION_PERIOD_ENUM.AFTER12 && endPeriod === PCS_COMPANION_PERIOD_ENUM.AFTER12) {
              return (
                form.getFieldValue('effective')?.datePicker?.startOf('d').valueOf() ===
                dayjs(endDate).startOf('d').valueOf()
              )
            }
          }}
        />
      ),
    },
  ]

  const onOk = async () => {
    if (!selList.length) {
      message.warning('请选择护工')
      return Promise.reject()
    }
    const values = await form.validateFields()
    return {
      nursingWorke: selList[0],
      ...values,
    }
  }

  return (
    <AekModal title='护工' onOk={onOk} width={1000} okText={isChange ? '更换' : '确定'}>
      <div>
        <span>订单号：{orderNo}</span>
        <span className='ml40px px'>姓名：{patientName}</span>
        <span className='ml40px px'>手机号：{phoneNo}</span>
      </div>
      <SearchForm className='mt10px' {...searchProps} />
      <div className='h350px flex flex-col'>
        <AekTable {...tableProps} />
      </div>
      {isChange && <AekForm form={form} formData={formData} />}
    </AekModal>
  )
}

SelNursingWorkerModal.PromiseThen = PromiseThen

export default SelNursingWorkerModal
